package org.vy.app.ajax.service.metadata;

import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import javax.servlet.http.HttpServletRequest;

import org.vy.app.ajax.IService;
import org.vy.dal.dao.lookup.ViewVyLookupCitiesDAO;
import org.vy.dal.dao.lookup.ViewVyLookupCitiesDO;

public class CountryMetaService implements IService<LocMetaResponse> {

	@Override
	public LocMetaResponse execute(Map<String, String> params, HttpServletRequest request) {
		LocMetaResponse rsp = new LocMetaResponse();
		try{
			String query=params.get("QUERY"),sv=params.get("STATE"),cnv=params.get("COUNTRY"),dv=params.get("DISTRICT");

			if("COUNTRY".equals(query)){
				List<ViewVyLookupCitiesDO> countries = ViewVyLookupCitiesDAO.findUniqueCountries();
				rsp.setCountry(getCountryMap(countries));
			}
			if("STATE".equals(query)|| (cnv!=null && !"".equals(cnv.trim())) ){
				List<ViewVyLookupCitiesDO> states = ViewVyLookupCitiesDAO.findStateByCountry(cnv);
				rsp.setState(getStateMap(states));
			}
			if("CITY".equals(query)|| (sv != null && !"".equals(sv)
					&& cnv != null && !"".equals(cnv))){
				List<ViewVyLookupCitiesDO> cities = ViewVyLookupCitiesDAO.findCitiesByStateAndCountry(sv, cnv);
				rsp.setCity(getCityMap(cities));
			}
		}catch(Exception e){
			e.printStackTrace();
		}
		return rsp;
	}
	
	private Map<String, String> getCountryMap(List<ViewVyLookupCitiesDO> lst){
		Map<String, String> map = new TreeMap<String, String>();
		for(ViewVyLookupCitiesDO rec : lst){
			map.put(rec.getCountryName(), rec.getCountryCode());
		}
		return map;
	}

	private Map<String, String> getStateMap(List<ViewVyLookupCitiesDO> lst){
		Map<String, String> map = new TreeMap<String, String>();
		for(ViewVyLookupCitiesDO rec : lst){
			map.put(rec.getStateName(), rec.getStateCode());
		}
		return map;
	}

	private Map<String, String> getCityMap(List<ViewVyLookupCitiesDO> lst){
		Map<String, String> map = new TreeMap<String, String>();
		for(ViewVyLookupCitiesDO rec : lst){
			map.put(rec.getCityName(), rec.getCityCode());
		}
		return map;
	}
}
